<template>
	<view class="player-wrap" ref="playWraper">
		<!-- {{isPlaying}} -->
		<view class="base-info">
			<!-- 基本信息 -->
			<p class="song-name">{{currentPlayInfo.name}}</p>
			<p class="singer-name">{{currentPlayInfo.singerInfo.name}}</p>
		</view>
		<view class="cover-wraper">
			<!-- 封面 -->
			<image class="cover" ref="cover" :src="currentPlayInfo.albumInfo.picUrl" mode="scaleToFill"></image>
		</view>

		<!-- 歌词 -->
		<div>
			<lyric :songLrc="songLrc" :current_time="current_time"></lyric>
		</div>
		<!-- 进度条 -->
		<play-progress :x="currentPercentX" :duration="duration" :current_time="current_time" @drageEvent="drageEvent"></play-progress>

		<div class="control">
			<span class="icon iconfont" @click="tooglePlayMethod">{{order==true?'&#xe625;':'&#xe62e;'}}</span>
			<span class="icon iconfont last" @click="lastSong">&#xe677;</span>
			<span class="icon iconfont play-pause play" v-if="!isPlay" @click="tooglePlayStatus">&#xe636;</span>
			<span class="icon iconfont play-pause pause" @click="tooglePlayStatus" v-else>&#xe771;</span>
			<span class="icon iconfont next" @click="nextSong">&#xe60c;</span>
			<span class="icon iconfont playlist">&#xe631;</span>
		</div>
		<!-- {{currentPlayInfo}} -->
	</view>
</template>

<script>
	import playProgress from "../../components/progress.vue"
	import lyric from "../../components/lyric.vue"
	import {
		mapActions
	} from "vuex"
	export default {
		data() {
			return {
				current_time: 0, //当前播放时间
				currentPercentX: 0, //当前播放百分比
				duration: 0, //歌曲市场
				isPlay: false, //是否正在播放,
				isInList: "",
				songList: [],
				order: true,
				songLrc: "",
			}
		},

		components: {
			playProgress,
			lyric
		},
		computed: {
			currentPlayInfo() {
				return this.$store.state.player.currentPlayInfo
			},
			audioContext() {
				return this.$store.state.player.audioPlayContext
			},
			isPlaying() {
				return this.$store.state.player.isPlaying
			}
		},
		methods: {
			...mapActions(["handleSaveCurrentPlayInfo", "handleSaveAudioContext", "handleTooglePlayStatus"]),
			async getSongDetail(ids) {
				const res = await Promise.all([
					this.rq.fetchGet(this.apiUrl.songDetails, {
						ids,
					}),
					this.rq.fetchGet(this.apiUrl.songUrl, {
						id: ids
					}),
					this.rq.fetchGet(this.apiUrl.songLyric, {
						id: ids
					})
				])

				const songsInfo = res[0][1].data.songs[0];
				const urlInfo = res[1][1].data;
				const info = {
					id: songsInfo.id,
					name: songsInfo.name,
					albumInfo: songsInfo.al,
					singerInfo: songsInfo.ar[0],
					playInfo: res[1][1].data.data[0]
				}
				const activeSongListStorage = await uni.getStorage({
					key: "activeSongList"
				})
				if (activeSongListStorage[1]) {
					this.songList = JSON.parse(activeSongListStorage[1].data);
					const songListIds = this.songList.map(item => item.id)
					songListIds.map((item, index) => {
						if (item == info.id) {
							this.isInList = index;
							return
						}
					})
				}
				if (!info.playInfo.url) {
					uni.showToast({
						title: "当前歌曲无法播放",
						icon: "none"
					})
					return;
				}
				if (this.audioContext) { //先判断有没有audio上下文
					if (info.id === this.currentPlayInfo.id) { //判断点击的id是否和当前一致
						// console.log('is playing current !')
					} else {
						// console.log('new songs !')
						//不一致，则代表点击了新的歌曲，audio上下文加载新的歌曲信息
						this.audioContext.stop()
						this.handleSaveCurrentPlayInfo(info); //更新新的歌曲的播放信息
						this.audioContext.src = info.playInfo.url //更新新的url
						this.audioContext.play() //播放
					}
				} else { //没有则创建一个新的audio上下文，并保存在全局的响应式变量。
					// console.log('first play !')
					const innerAudioContext = uni.createInnerAudioContext();
					this.handleSaveAudioContext(innerAudioContext); //创建新的audiocontext
					this.handleSaveCurrentPlayInfo(info); //提交当前播放信息
					this.audioContext.src = info.playInfo.url //设置url
					this.audioContext.autoplay = true; //自动播放
				}
				this.audioContext.onCanplay(() => {
					this.isPlay = true;
				});
				this.audioContext.onTimeUpdate(() => {
					if (this.$refs.cover) {
						this.$refs.cover.$el.style.animationPlayState = "running"
						this.$refs.playWraper.$el.style.animationPlayState = "running"
					}
					this.duration = this.audioContext.duration
					this.currentPercentX = this.audioContext.currentTime / this.audioContext.duration
					this.current_time = this.audioContext.currentTime;
					this.handleTooglePlayStatus(this.isPlay)
				})

				this.audioContext.onPause(() => {
					if (this.$refs.cover) {
						this.$refs.cover.$el.style.animationPlayState = "paused"
						this.$refs.playWraper.$el.style.animationPlayState = "paused"
						// this.handleTooglePlayStatus(false)
					}
				})
				this.audioContext.onEnded(() => {
					if (this.$refs.cover) {
						this.handleTooglePlayStatus(false)
						// this.$refs.cover.$el.style.animationPlayState = "paused"
						this.nextSong();

					}
				})
				this.songLrc = res[2][1].data.lrc ? res[2][1].data.lrc.lyric : null;
			},
			drageEvent(timing) {
				if (this.isPlay) {
					this.audioContext.seek(timing)
				}
			},
			tooglePlayStatus() {
				if (this.isPlay) {
					this.audioContext.pause()
				} else {
					this.audioContext.play()
				}
				this.isPlay = !this.isPlay
				this.handleTooglePlayStatus(this.isPlay)
			},

			lastSong() {
				this.toogleMusic(-1)
			},
			nextSong() {
				this.toogleMusic(1)
			},
			toogleMusic(position) {
				if (this.songList.length == 0) {
					uni.showToast({
						title: "当前播放列表就这一首歌",
						icon: "none"
					})
					return
				}
				if (this.order) {
					if (this.isInList > 0 && this.isInList < this.songList.length - 1) {
						this.getSongDetail(this.songList[this.isInList + position].id);
					} else if (this.isInList === this.songList.length - 1) {
						position > 0 ? this.getSongDetail(this.songList[0].id) : this.getSongDetail(this.songList[this.isInList - 1].id)
					} else if (this.isInList === 0) {
						position > 0 ?
							this.getSongDetail(this.songList[this.isInList + 1].id) : this.getSongDetail(this.songList[this.songList
								.length - 1].id)
					} else {
						this.getSongDetail(this.songList[0].id)
					}
				} else {
					const randomIndex = Math.floor(Math.random() * this.songList.length);
					this.getSongDetail(this.songList[randomIndex].id)
				}
			},
			tooglePlayMethod() {
				this.order = !this.order;
				uni.showToast({
					title: `切换为${this.order?'顺序播放':"随机播放"}`,
					icon: "none"
				})
			},
		},
		onLoad() {
			if (this.audioContext && !this.audioContext.paused) {
				this.isPlay = true;
			}
			this.getSongDetail(this.options.id);
		},
		onUnload() {

		}
	}
</script>

<style lang="scss">
	.player-wrap {
		width: 100%;
		min-height: 100vh;
		background: linear-gradient(39deg, #C94556 0%, #015BA6 50%, #D5732F 100%);
		background-size: 200% 100%;
		background-position: center center;
		overflow: hidden;
		display: flex;
		flex-direction: column;
		justify-content: space-around;
		animation: bgRun 2s ease-in-out infinite alternate-reverse;

		.base-info {
			text-align: center;
			font-size: .8rem;
			color: #FFFDEF;
			margin-top: 2rem;

			.song-name {
				font-size: .9rem;
			}
		}

		.cover-wraper {
			text-align: center;

			.cover {
				width: 50vw;
				height: 50vw;
				margin-top: 2rem;
				border-radius: 50%;
				border: 10px solid #fdfdfd;
				animation: coverPlay 5s linear infinite;
				animation-play-state: paused; //默认动画为暂停
				box-shadow: 0px 0px 40px #56dae2;
				opacity: .8;
			}
		}

		.control {
			width: 100%;
			display: flex;
			justify-content: space-around;
			align-items: center;

			.icon {
				font-size: 1.4rem;
				color: #FFFFFF;

				&:focus {
					color: red;
				}
			}

			.play-pause {
				font-size: 2.5rem;
			}
		}

	}

	@keyframes coverPlay {
		from {
			transform: rotateZ(0deg);
		}

		to {
			transform: rotateZ(360deg);
		}
	}

	@keyframes bgRun {
		from {
			background-position: 0 0;
		}

		to {
			background-position: 100% 0;
		}
	}
</style>
